package cn.dvptech.remotemate.screenmirror.screenHelper;

import android.view.SurfaceView;
import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
/**
 * author  : ulongx
 * website : www.dvptech.cn
 * date    : 2024/7/28
 * desc    :
 */
public class AutoFitSurfaceView extends SurfaceView {

    private int videoWidth = 0;
    private int videoHeight = 0;

    public AutoFitSurfaceView(Context context) {
        super(context);
        init();
    }

    public AutoFitSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AutoFitSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                // Surface created, you can start the video playback here if needed
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                adjustAspectRatio(width, height);
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // Surface destroyed, stop the video playback here if needed
            }
        });
    }

    public void setVideoSize(int width, int height) {
        videoWidth = width;
        videoHeight = height;
        adjustAspectRatio(getWidth(), getHeight());
    }

    private void adjustAspectRatio(int viewWidth, int viewHeight) {
        if (videoWidth == 0 || videoHeight == 0) {
            // Default behavior when video size is not set yet
            return;
        }

        double aspectRatio = (double) videoHeight / videoWidth;
        int newWidth, newHeight;
        if (viewHeight > (int) (viewWidth * aspectRatio)) {
            newWidth = viewWidth;
            newHeight = (int) (viewWidth * aspectRatio);
        } else {
            newHeight = viewHeight;
            newWidth = (int) (viewHeight / aspectRatio);
        }

        int xOff = (viewWidth - newWidth) / 2;
        int yOff = (viewHeight - newHeight) / 2;

        getHolder().setFixedSize(newWidth, newHeight);
        setTranslationX(xOff);
        setTranslationY(yOff);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        adjustAspectRatio(width, height);
        setMeasuredDimension(width, height);
    }

}
